寫程式,處理資料是家常便飯,然而資料小則幾百例,多則 ... 非常多!
因此有一套標準的處理流程,會讓 developer 更方便,對吧?
The iterator pattern has been around for decades, and suggests a "standardized" approach to consuming data from a source one chunk at a time. The idea is that it's more common and helpful to iterate the data source—to progressively handle the collection of data by processing the first part, then the next, and so on, rather than handling the entire set all at once.
簡單來說,把資料想成未切過的大披薩,而 iterator pattern 會將這一大塊披薩,切成好幾個小披薩,然後一個個處理。
起出 ES6 定義了 next() 方法,其會回傳 value 及 done,如果 done 是 true,那麼才可以往下一個 iterration 前進(下一塊小披薩),看參考。
後來,這個方法逐漸地很少人使用了,因為太麻煩,每次都要使用 next() 處理下一個資料; 因此 ES6 又定義了一些 APIs 來標準化這個 iteration 。
最常見的就是 for ... of
var numbers = ['1', '2', '3'];
for (let number of numbers) {
console.log(`Iterator value: ${ val }`);
}
...
operator... operator 有兩種相對的形式 (symmetrical forms):
spread operator
顧名思義,這個運算子用來「發散」,為什麼會提到 spread operator?
因為在 JS 有兩個情況可以 spread iterator :
// An array spread:
// spread an iterator into an array,
// with each iterated value occupying
// an array element position.
var valus = [ ...it ];
// A function call spread:
// spread an iterator into a function,
// call with each iterated value
// occupying an argument position.
doSimethingUseful( ...it );
範例中的 it
就是 iterator,這個 iterator 會被 spread 進陣列,或者 arguments 裡。
An iterable is a value that can be iterated over.
Iterate 通常會叫做「遍例」,所以可以被遍例的 value 被稱作 iterable。Strings, arrays, maps, sets
等等都是 iterable,參考 mdn。
// A string is an iterable
var greeting = 'Hello';
var char = [...greeting];
console.log(char); // 'H','e','l','l','o'
// An array is an iterable
var arr = [10, 20, 30];
for (let val of arr) {
console.log(`Array value: ${ val }`);
}
// A map data structure is composed of multiple key-value pairs.
// Any value may be used as a key or a value.
// A map is organized as linked list, so the order is maintained,
// and thus, a map is an iterable
var sibilings = new Map();
sibilings.set('sister': 'Alice');
sibilings.set('brother': 'Adam');
// array destructuring
for (let [sibiling, name] of sibilings) {
console.log(`My ${ sibiling } is ${ name }`);
}
// My sister is Alice
// My brother is Adam
// values() methods
for (let name of sibilings.values()) {
connsole.log(`${ name }`);
}
// Alice
// Adam
// entries() methods
for (let [idx, val] of sibilings.entries()) {
console.log(`[${ idx }]: ${ val }`);
}
// [0]: Alice
// [1]: Adam
補充:所有 iterable 都有 keys()
, values()
, 和 entries()
的方法。